package main

import (
	"encoding/json"
	"fmt"
)

func mapToJson(m map[string]interface{}) (ret string, err error)  {
	//data, err := json.Marshal(&m)
	data, err := json.Marshal(m)  // 这两种都可以 ???????????????????????????????
	if err != nil {
		err = fmt.Errorf("json marshal failed, err: ", err)
		return "", err
	}

	return string(data), nil
}

func jsonToMap(data string) (map[string]interface{}, error) {
	//var m map[string]interface{}
	m := make(map[string]interface{})
	err := json.Unmarshal([]byte(data), &m) //这怎么知道它要的是指针呢

	if err != nil {
		fmt.Println("unmarshal failed, err: ", err)
		return nil, err
	}

	return m, nil
}

func tJson() {
	m := make(map[string]interface{})

	m["username"] = "cs"
	m["age"] = 24
	m["sex"] = "M"

	jsonStr, _ := mapToJson(m)
	fmt.Println(jsonStr)

	//m, _ = jsonToMap(jsonStr)
	//fmt.Println(m)

	m, _ = jsonToMap("{\"ttlMonitorSleepSecs\":3}")

	//unmarshal failed, err:  invalid character 't' looking for beginning of object key string
	//m, _ = jsonToMap("{ttlMonitorSleepSecs:3}")
	fmt.Println(m)

	////////////////// list of map to json
	s := []map[string]interface{}{}

	m1 := map[string]interface{}{"name": "John", "age": 10}
	m2 := map[string]interface{}{"name": "Alex", "age": 12}

	s = append(s, m1, m2)

	b, err := json.Marshal(s)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}

	fmt.Println("marshal list of map:", string(b))


	// struct to json
	type User struct {
		Name string
	}
	user := User{Name: "cshi"}
	j, err := json.Marshal(user)
	fmt.Println("struct to json:", string(j))
}

func main() {
	tJson()

}
